package com.newear.base.ui.circlecamera;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.newear.util.HardWare;
import com.newear.util.MyLogger;

/**
 * Created by dong on 2018/5/23.
 */

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";

    private Camera mCamera;
    private Camera.CameraInfo cameraInfo;
    private SurfaceHolder mHolder;
    private Activity mContext;
    private CameraListener listener;
    private int cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
    private int displayDegree = 90;
    private int type;
    public interface Type {
        int FACE = 1;
        int TONGUE = 2;
    }

    public CameraPreview(Activity context, int type) {
        super(context);
        this.type = type;
        mContext = context;
        //mCamera = Camera.open(cameraId);

        Camera.CameraInfo tempCameraInfo = new Camera.CameraInfo();
        int cameraCount = Camera.getNumberOfCameras(); // get cameras number
        for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
            Camera.getCameraInfo(camIdx, tempCameraInfo); // get camerainfo
            MyLogger.e("josan", "camIdx :" + camIdx + ",cameraInfo.facing:" + tempCameraInfo.facing);
            if (tempCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { // 代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
                try {
                    cameraInfo = tempCameraInfo;
                    mCamera = Camera.open(camIdx);
                    Camera.Parameters p = mCamera.getParameters();
                    p.setExposureCompensation(p.getMaxExposureCompensation() / 8);
                    if (p.isZoomSupported()) {
                        // 设置相机预览的缩放，这里默认最大值的2/3,可根据实际值调节
                        if (type == Type.FACE) {    // 脸诊
                            p.setZoom( p.getMaxZoom() * 1 / 5);
                            mCamera.setParameters(p);
                        } else if (type == Type.TONGUE){    // 舌诊
                            p.setZoom( p.getMaxZoom() * 3 / 4);
                            mCamera.setParameters(p);
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        mHolder = getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCameraListener(CameraListener listener) {
        this.listener = listener;
    }

    /**
     * 拍照获取bitmap
     */
    public void captureImage() {
        try {
            mCamera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean success, Camera camera) {
                    camera.takePicture(null, null, new Camera.PictureCallback() {
                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                            Log.e("josan", "size:" + data.length / 1024.0 + "kb");
                            if (null != listener) {
                                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                                    displayDegree = displayDegree + 180;
                                }
                                listener.onCaptured(HardWare.rotateBitmap(BitmapFactory.decodeByteArray(data, 0, data.length)));
                            }
                        }
                    });
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            if (null != listener) {
                listener.onCaptured(null);
            }
        }
    }

    /**
     * 预览拍照
     */
    public void startPreview() {
        mCamera.startPreview();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != mCamera) {
            mCamera.autoFocus(null);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        startCamera(holder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (mHolder.getSurface() == null) {
            return;
        }
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            startCamera(mHolder);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    private void startCamera(SurfaceHolder holder){
        try {
            mCamera.setPreviewDisplay(holder);
            setCameraDisplayOrientation(mContext, cameraId, mCamera);
            Camera.Parameters parameters = mCamera.getParameters();
            Camera.Size preSize = getCameraSize();
            DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
            MyLogger.e("josan", "preview size,height:" + preSize.height + ",width:" + preSize.width + ",ratio:" + preSize.width * 1.0 / preSize.height);
            // 修正，避免拉伸
            parameters.setPreviewSize(preSize.width, preSize.height);
            parameters.setPictureSize(preSize.width, preSize.height);
            parameters.setJpegQuality(100);
            mCamera.setParameters(parameters);
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Camera.Size getCameraSize() {
        if (null != mCamera) {
            Camera.Parameters parameters = mCamera.getParameters();
            DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
            Camera.Size preSize;
            if (android.os.Build.MODEL.contains("ONEPLUS A3010")) {
                preSize = Util.getCloselyPreSize(true, metrics.widthPixels, metrics.heightPixels,
                        parameters.getSupportedPreviewSizes());
            } else {
                preSize = Util.getCloselyPreSize(false, metrics.widthPixels, metrics.heightPixels,
                        parameters.getSupportedPreviewSizes());
            }
            Log.e("josan", "metrics.widthPixels：" + metrics.widthPixels + ",metrics.heightPixels：" + metrics.heightPixels);
            return preSize;
        }
        return null;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }


    /**
     * Android API: Display Orientation Setting
     * Just change screen display orientation,
     * the rawFrame data never be changed.
     */
    private void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            displayDegree = (info.orientation + degrees) % 360;
            displayDegree = (360 - displayDegree) % 360;  // compensate the mirror
        } else {
            displayDegree = (info.orientation - degrees + 360) % 360;
        }
        Log.e("josan:", "设置的角度："+ displayDegree);
        //这里为了设配大屏幕摄像头,写死
        Log.e("josan", "手机型号：" + android.os.Build.MODEL);
        if (android.os.Build.MODEL.contains("ONEPLUS A3010")) {
            camera.setDisplayOrientation(displayDegree);
        } else {
            camera.setDisplayOrientation(180);
        }
    }

    /**
     * 释放资源
     */
    public synchronized void releaseCamera() {
        try {
            if (null != mCamera) {
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();//停止预览
                mCamera.release(); // 释放相机资源
                mCamera = null;
            }
            if (null != mHolder) {
                mHolder.removeCallback(this);
                mHolder = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}